package websocket;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

//访问路径为 ws://127.0.0.1:8080/websocket_java/WSServer/XX(最后一位任意值{}取值)
@ServerEndpoint("/WSServer/{user}")
public class WSServer {
	
    private String currentUser;
    private int sum=1;
    
    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
   
    private static Map<String, WSServer> clients = new ConcurrentHashMap<String, WSServer>(); 
    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    @SuppressWarnings("unused")
	private Session session;
    
    

	//连接打开时执行
    @OnOpen
    public void onOpen(@PathParam("user") String user, Session session) throws UnsupportedEncodingException  {
    	   this.session = session;
    	   clients.put(session.getId(), new WSServer() );
    	   addOnlineCount(); // 在线数加1
           System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
           
    	//解码中文参数
    	currentUser =  new String(user.getBytes("ISO-8859-1"),"UTF-8"); 
        System.out.println("Connected ...sessionID= " + session.getId());
   
    }

    //收到消息时执行
    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + currentUser + ":" + message+"Connected...sessionID="+ session.getId());
 
        while(true) {
        	sum++;
    	   return  "我是服务端我收到你消息了=" +currentUser + ":" + sum;
       }
    }


 
    //连接关闭时执行
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
    		this.session = session;
    		if(!session.getId().isEmpty()) {
    			clients.remove(session.getId()); //
    		}
    		subOnlineCount(); // 在线数减1
    		
           System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
          
    	
        System.out.println(String.format("SessionID= %s 关闭原因 %s", session.getId(), closeReason));
    }

    //连接错误时执行
    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }
    
    
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
    	WSServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
    	WSServer.onlineCount--;
    }
    
    
    
    
 
    public void count() {
    
        new Timer().schedule(new TimerTask() {
            
            @Override
            public void run() {
            
            }
        }, 0, 3000);//3秒执行一次 
		
      
    	
    }
    
    
  
}